package lg.minecraft.plugin.library.common;

import lg.minecraft.plugin.library.config.LGBaseConfig;
import lombok.Getter;
import org.bukkit.plugin.Plugin;

import java.io.File;
import java.util.Objects;

/**
 * @author langle__
 * @version 1.0
 */
public class FileListener {

    private final LGBaseConfig config;
    @Getter
    private final Plugin plugin;
    private final File file;
    private long lastModifiedTime = 0;

    public FileListener(LGBaseConfig config) {
        this.config = config;
        this.plugin = config.getPlugin();
        this.file = config.getFile();
    }

    public void updateLastModifiedTime() {
        if (!file.exists()) return;
        this.lastModifiedTime = file.lastModified();
    }

    public boolean isFileModified() {
        if (!file.exists()) return false;
        long currentModifiedTime = file.lastModified();
        if (lastModifiedTime != currentModifiedTime) {
            this.lastModifiedTime = currentModifiedTime;
            return true;
        }
        return false;
    }

    public void canLoadConfig() {
        if (!this.isFileModified()) return;
        this.loadConfig();
    }

    public void loadConfig() {
        config.load();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof FileListener)) return false;
        FileListener that = (FileListener) o;
        return Objects.equals(file, that.file);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(file);
    }

    @Override
    public String toString() {
        return "FileListener{" +
                "file=" + file.getAbsolutePath() +
                '}';
    }

}
